package com.rockxin.cat.network;

import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Lans on 2017/3/9.
 */

public class RetrofitUtils {
    private Retrofit retrofit = null;
    private OkHttpClient.Builder builder = null;

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final RetrofitUtils INSTANCE = new RetrofitUtils();
    }

    //获取单例
    public static RetrofitUtils getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 初始化
     */
    public RetrofitUtils() {
        builder = new OkHttpClient.Builder();
        //设置超时
        builder.connectTimeout(NetWorkConfig.TIME_OUT, TimeUnit.SECONDS);
        builder.readTimeout(NetWorkConfig.READ_TIME, TimeUnit.SECONDS);
        builder.writeTimeout(NetWorkConfig.WRITE_TIME, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        //设置log拦截器
        if (NetWorkConfig.DEBUG) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(httpLoggingInterceptor);
        }

        //添加请求头
        builder.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                request.newBuilder()
                        .addHeader("Content-Type", "text/json;charset=UTF-8")
                        .build();
                return chain.proceed(request);
            }
        });
    }

    /**
     * @param cls
     * @param <T>
     * @return
     */
    public <T> T create(final Class<T> cls) {
        retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().serializeNulls().create()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(NetWorkConfig.APPURL)
                .build();
        return retrofit.create(cls);
    }

    /**
     * @param observable
     * @param subscriber
     * @param <T>
     */
    public <T> void toSubscribe(Observable<T> observable, Subscriber<T> subscriber) {
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }
}
